package jw.hospital.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jw.hospital.cmn.listener.DicListener;
import jw.hospital.cmn.service.DictService;
import jw.hospital.cmn.mapper.DictMapper;
import jw.hospital.hosp.model.cmn.Dict;
import jw.hospital.hosp.vo.DictVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private DictMapper dictMapper;
    ;

    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictVo.class, new DicListener(dictMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

    @Override
    public void exportDictData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        List<Dict> dictList = dictMapper.selectList(null);
        List<DictVo> dictVoList = new ArrayList<>();
        for (Dict dict : dictList) {
            DictVo dictVo = new DictVo();
            BeanUtils.copyProperties(dict, dictVo);
            dictVoList.add(dictVo);
        }
        try {
            EasyExcel.write(response.getOutputStream(),DictVo.class).sheet().doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
